import { defineStore } from "pinia";
import cookie from 'js-cookie'//引入处理cookies的Api
import { ElMessage } from 'element-plus'//提示信息
import router from '@/router'//路由
import { reactive, ref } from 'vue'//引入ref,实现数据响应式
import { post } from "@/utils/http";

export const useUserStore = defineStore('UserStore', () => {
    let user = ref((<UserInfo>{})); //个人信息数据

    let loginInfo = reactive({ username: '', password: '' });//登录账号密码

    let permissionList = ref<string[]>([])//权限数据

    const setUser = (data: UserInfo) => { //在login页面调用，传递参数并赋值
        user.value = data;
        permissionList.value = user.value.perms;
    };
    
    const loginOut = () => { //退出登录
        post({ _gp: 'admin', _mt: 'logout' }).then((res) => {
            console.log(res);
            let { errmsg, errno } = res
            if (200 == errno) {
                user.value = (<UserInfo>{})//清空个人信息数据
                cookie.remove('token')//清空cook里存储的token头
                router.replace('/login')//跳转登录页面
            } else {
                router.replace('/login')
                ElMessage.error(errmsg)//错误提示
            }
        }).catch((err) => {
            console.log(err);
        });
    }
    return {
        user, loginInfo, permissionList, setUser, loginOut
    }
}, {
    persist: true,//开启持久化
})